/**
 * Created by alice on 2017/2/17 0017
 */
var ip = null;
var channel = 0;	//通道号
var _data;//获取播放视频列表数据
var now_video = utils.get_url_param('vlcCourtUid');
var videoNum = utils.get_url_param("videonum") || 0;	//录像号
var url_data = [];//存储所有的播放地址
var now_url = null;//当前播放地址

;-function (window) {
    "use strict";
    //TODO 预设变量写这里，全局变量写在base.js 里面 使用 r. 调用
    var ready = {
        layer: null,
    };
    //TODO 初始化的方法写这里面
    var init = function () {
        init_ready();//加载预设变量
        init_event();

        function init_event() {//TODO 初始化页面事件
            $("#_nav_court_info").click(function () {
                $("#_nav_court_p").attr("class", "");
                $("#_nav_court_note").attr("class", "");
                $("#_nav_court_info").attr("class", "active");
                $("#_court_info").show();
                // $("#_court_case").hide();
                $("#_court_note").hide();
                $("#_nav_court_note_down").hide();
            });
            $("#_nav_court_note").click(function () {
                $("#_nav_court_info").attr("class", "");
                $("#_nav_court_p").attr("class", "");
                $("#_nav_court_note").attr("class", "active");
                $("#_court_info").hide();
                // $("#_court_case").hide();
                $("#_court_note").show();
                $("#_nav_court_note_down").show();
            });
            $("#_nav_court_p").click(function () {
                $("#_nav_court_p").attr("class", "active");
                $("#_nav_court_note").attr("class", "");
                $("#_nav_court_info").attr("class", "");
                $("#_court_info").hide();
                // $("#_court_case").show();
                $("#_court_note").hide();
            });
            $("#channels").change(function () {
                var now = vlc.input.time;
                channelChange();
                doSetSlider(now);
            });
            $("#videos").change(function () {
                initdown($("#videos").val());
            });
            $("#imageLoad").attr("href", r.base_path + 'my/screenshot');
            Class.init();
            Class.init_select();
            Class.init_record();
        }

        function init_ready() {//TODO 初始化预设值
            layui.use('layer', function () {
                ready.layer = layui.layer;
            });

        }
    };
    //TODO 内部调用的方法写这里
    var Class = {
        init: function () {
            //记录案件名称、案号，并向后台发送点播信息
            Class.vod_ws();
            var judge_user_uid = major_plan.judgeUserUid;
            var secretary_uid = major_plan.secretaryUserUid;
            var courtroomName = major_plan.courtRoomName;
            var statusName = '';
            switch (major_trial.status) {
                case 0:
                    statusName = '排期';
                    break;
                case 1:
                    statusName = '正在开庭';
                    break;
                case 2:
                    statusName = '休庭';
                    break;
                case 3:
                    statusName = '闭庭';
                    break;
                case 4:
                    statusName = '归档';
                    break;
                case 5:
                    statusName = '正在开庭';
                    break;
                default :
                    statusName = '未知';
            }
            var parties = major_case.accuse + " " + major_case.accused;
            var startDate = major_case.createDate;
            // startDate = startDate.substring(0, startDate.length - 2);
            var planDate = '';
            if (major_trial.startDate) {
                var start_date = new Date(major_plan.startDate);
                planDate = start_date.getFullYear() + '-' + (start_date.getMonth() + 1) + '-' + start_date.getDate() + ' ' + start_date.getHours() + ':' + start_date.getHours();
            }
            var endDate = '';
            if (major_trial.endDate) {
                var end_date = new Date(major_plan.endDate);
                endDate = end_date.getFullYear() + '-' + (end_date.getMonth() + 1) + '-' + end_date.getDate() + ' ' + end_date.getHours() + ':' + end_date.getHours();
            }
            var archives = major_case.archives;
            var caseName = major_case.name;
            var title_text = '&nbsp;' + archives + '——' + caseName;
            if (title_text.length > 50) {
                title_text = title_text.substring(0, 50) + '...';
            }
            $("#title").html(title_text);
            var html = ['  <div class="cmp-play-text">',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>案  号：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + archives + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>案件类型：</span>',
                '                            </div>',
                '                            <div class="col-md-3 col-xs-8 text-left">',
                '                                <span>' + major_case.caseType + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>案件名称：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + caseName + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>审判长：</span>',
                '                            </div>',
                '                            <div class="col-md-3  col-xs-8 text-left">',
                '                                <span><a id="judge_name" class="white-a">' + (major_plan.judgeName ? major_plan.judgeName : '') + '</a></span>',
                '                            </div>',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                            </div>',
                '                            <div class="col-md-3  col-xs-8 text-left">',
                '                            </div>',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>书记员：</span>',
                '                            </div>',
                '                            <div class="col-md-3  col-xs-8 text-left">',
                '                                <span><a id="secretary_name" class="white-a">' + (major_plan.secretaryName ? major_plan.secretaryName : '') + '</a></span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>当事人：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + parties + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>开庭地点：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + (courtroomName ? courtroomName : '') + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>排期时间：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + planDate + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>开庭时间：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + startDate + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>闭庭时间：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + endDate + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>庭审状态：</span>',
                '                            </div>',
                '                            <div class="col-md-3 col-xs-8 text-left">',
                '                                <span>' + statusName + '</span>',
                '                            </div>',
                '                        </div>',
                '                        <div class="row row-court">',
                '                            <div class="col-md-3 col-xs-4 text-right">',
                '                                <span>基本案情：</span>',
                '                            </div>',
                '                            <div class="col-md-9 col-xs-8 text-left">',
                '                                <span>' + major_case.summary + '</span>',
                '                            </div>',
                '                        </div>',
                '                    </div>'].join("");
            $("#_court_info").append(html);
            $("#judge_name").attr("href", judge_user_uid?r.base_path + "more/more_review?judge=" + judge_user_uid + "&city=" + now_video + '&courtUid=' + r.court_uid:'javascript:void(0);');
            $("#secretary_name").attr("href", secretary_uid?r.base_path + "more/more_review?secretary=" + secretary_uid + "&city=" + now_video + '&courtUid=' + r.court_uid:'javascript:void(0);');
            $("#loading").hide();
        },
        vod_ws: function () {
            var userName = $.cookie('_username');
            var data = {
                caseUid: major_case.uid,
                userName: userName,
                courtUid: r.court_uid,
                userCourtUid: r.user_court_uid,
                planUid: major_plan.uid,
                archives: major_case.archives,
                name: major_case.name,
                type: major_case.caseType,
                vod: "1"
            };
            data = JSON.stringify(data);
            create_ws(data);
        },
        init_select: function () {
            //构造点播通道select
            var chn = [];
            $.each(major_video, function (i, n) {
                if (chn.indexOf(n.channelsName) == -1) {
                    $("#channels").append("<option value='" + n.channelsName + "'>" + n.channelsName + "</option>");
                    chn.push(n.channelsName);
                }

                if (n.startRecTime) {
                    var startRecTime = new Date(n.startRecTime);
                    n.startRecTime = (startRecTime.getHours() > 9 ? startRecTime.getHours() : "0" + startRecTime.getHours()) + ":" + (startRecTime.getMinutes() > 9 ? startRecTime.getMinutes() : "0" + startRecTime.getMinutes());
                } else {
                    n.startRecTime = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                if (n.endRecTime) {
                    var endRecTime = new Date(n.endRecTime);
                    n.endRecTime = (endRecTime.getHours() > 9 ? endRecTime.getHours() : "0" + endRecTime.getHours()) + ":" + (endRecTime.getMinutes() > 9 ? endRecTime.getMinutes() : "0" + endRecTime.getMinutes());
                } else {
                    n.endRecTime = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }
            });
            //获取url的点播通道号进行选中点播通道的select，如果为空则初始化
            if (channel == null && $("#channels>option").length != 0) {
                channel = 1;
            } else {
                $("#channels>option").eq(channel).attr("selected", "selected");
            }
            console.log('change')
            //调用方法进行构造点播录像select
            channelChange(videoNum);
            //尝试获取url中点播的视频编号进行选中点播录像select，如果为空则初始化
            $("#videos>option:eq(" + parseInt(videoNum) + ")").attr("selected", "selected");

        },
        init_record: function () {
            $.post(r.base_path + "video/courtrecForId", {
                planUid: major_plan.uid,
                courtUid: major_case.courtUid
            }, function (result) {
                if (result && result.data) {
                    $("#notetext").html(result.data[0]);
                    //绑定笔录下载地址--基于http下载
                    $("#noteLoad").attr("href", result.data[1]);
                }
            }, 'json');
        }
    };
    init();
    //TODO 对外公开的方法写在这里
    window.p = {
        init_playlist:Class.init_playlist
    };
}(window);

function channelChange(num) {
    num = num || 0;
    channel = $("#channels").val();
    var i = 0;
    //清空select
    $("#videos").html("");
    $.each(major_video, function (j, n) {
        var temp = $("#channels").val();
        if (n.channelsName == temp) {
            $("#videos").append("<option value=\"" + i + "\">" + n.startRecTime + "—" + n.endRecTime + "</option>");
            i++;
        }
    });
    console.log(num, channel, _data);
    vlc_playlist = [];
    $.each(major_video, function (i, n) {
        if (n.channelsName == channel) {
            vlc_playlist.push(n);
        }
    });
    init_playlist(num);
}

function initdown(num) {
    if (vlc) {
        //获取当前视频url地址
        now_url = url_data[num];
        vlc.playlist.playItem(num);
        // console.log("href", "http://" + _data[num].url + ":8200/" + _data[num].filename);
    }
}

//单个文件下载
function down() {
    var down_data = eval($("#data").val());
    //获取当前选中的通道图像
    var name = $("#channels").find("option:selected").text();
    if (name == null && name == "") {
        return;
    }
    //根据图像名称，获取这个通道图像的所有视频
    var channel_data = [];
    for (var index in down_data) {
        if (down_data[index].channelsName == name) {
            //拼接真实下载地址
            upload_url = "http://" + down_data[index].url + ":8200/" + down_data[index].fileName;
            //upload_url="http://"+down_data[index].url+":8080/"+down_data[index].filename;
            channel_data.push(upload_url);
        }

    }
    //真实模拟(多视频文件下载)
    if (channel_data["length"] > 0) {
        //测试使用
        //var downloadUrl = ['http://localhost:8080/ssm/videos/2.mp4','http://localhost:8080/ssm/videos/1.mp4'];
        var downloadUrl = channel_data;
        //页面动态生成a标签，模拟用户多个点击事件
        //清空原来下面的a标签
        $("#table").empty();
        for (var index in downloadUrl) {
            var count = parseInt(index, 0) + 1;
            var tr = "<tr><td style='border:1px solid blue;text-align:center;height:40px;'><a download  style='font-size:20px;text-decoration:underline;'  id='" + index + "'href='" + downloadUrl[index] + "'>" + name + "_" + count + ".mp4</a></td></tr>";
            //放在页面上，触发点击事件
            $("#table").append(tr);
            //触发点击事件
            //document.getElementById(""+index).click();
        }
        //先绑定数据到模态框上面
        /* 完成拖拽 */
        $("#download_video").draggable({
            cursor: "move",
            handle: '.modal-header'//--指定只有拖拽头部，才能拖拽
        });
        //显示模态框
        $("#download_video").modal("show");

    }
}

function play() {
    $.ajax({
        url: r.base_path + "playConvert",
        type: 'post',
        async: false,
        dataType: "text",
        data: {
            planId: planId,
            courtId: now_video,
            channel: channel,
            videoNum: videoNum
        },
        success: function (result) {
            initdown(result);
        }
    });
}

function initialise(courtIp, cfg) {
    // console.log("rtsp://" + courtIp + "/" + cfg);
    var vlc = getVLC("vlc");
    if (vlc) {
        vlc.playlist.items.clear();
        while (vlc.playlist.items.count > 0) {
            // clear() may return before the playlist has actually been cleared
            // just wait for it to finish its job
        }
        var options = [":rtsp-tcp"];
        var itemId = vlc.playlist.add("rtsp://" + courtIp + "/" + cfg, "", options);
        if (itemId != -1) {
            vlc.playlist.playItem(itemId);
        }
        else {
            alert("cannot play at the moment !");
        }
    }
}

function doSetSlider(time) {
    var vlc = getVLC("vlc");
    if (vlc) {
        doPlayOrPause();
//        vlc.input.time = (time);
        window.setTimeout(doPlayOrPause, 500);
    }
}


function doPlayOrPause() {
    var vlc = getVLC("vlc");
    if (vlc) {
        vlc.playlist.togglePause();
    }
}


function formatTime(timeVal) {
    if (typeof timeVal != 'number')
        return "-:--:--";
    var timeHour = Math.round(timeVal / 1000);
    var timeSec = timeHour % 60;
    if (timeSec < 10)
        timeSec = '0' + timeSec;
    timeHour = (timeHour - timeSec) / 60;
    var timeMin = timeHour % 60;
    if (timeMin < 10)
        timeMin = '0' + timeMin;
    timeHour = (timeHour - timeMin) / 60;
    if (timeHour > 0)
        return timeHour + ":" + timeMin + ":" + timeSec;
    else
        return timeMin + ":" + timeSec;
}

function onPause() {
}

//抓怕函数
function catch1() {
    //获取当前毫秒数
    var currentTimeMills = doGetPosition();
    //转成秒数
    var time = parseInt(currentTimeMills / 1000);
    //请求后台真真的抓拍功能
    catchImage(time);
}

function doGetPosition() {
    var vlc = getVLC("vlc");
    if (vlc) {
        return vlc.input.time;

    }
}

function formatTime1(value) {

    var theTime = parseInt(value / 1000);// 秒

    var theTime1 = 0;// 分

    var theTime2 = 0;// 小时

    if (theTime > 60) {

        theTime1 = parseInt(theTime / 60);

        theTime = parseInt(theTime % 60);

        if (theTime1 > 60) {

            theTime2 = parseInt(theTime1 / 60);

            theTime1 = parseInt(theTime1 % 60);

        }

    }

    var result = "" + parseInt(theTime) + "秒";

    if (theTime1 > 0) {

        result = "" + parseInt(theTime1) + "分" + result;

    }

    if (theTime2 > 0) {

        result = "" + parseInt(theTime2) + "小时" + result;

    }

    return result;

}

var start = '';
var end = '';
//刷新清空当前数据
$("#startText").val('');
$("#endText").val('');

function start1() {
    var position = doGetPosition();
    start = parseInt(position / 1000);
    $("#startText").val(formatTime1(position));
}

function end1() {
    var position = doGetPosition();
    end = parseInt(position / 1000);
    $("#endText").val(formatTime1(position));
}

function catchImage(time) {
    document.getElementById("catch1").disabled = true;
    $.ajax({
        "type": "post",
        "url": r.base_path + 'image/catchImage?' + new Date().getTime(),
        "dataType": "json",
        "data": {
            time: time,
            url: now_url,
            planUid: major_plan.uid
        },
        "success": function (data) {
            if (result&&result.code==0) {
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.msg('抓拍成功');
                });
                var date = new Date();
                var d = result.data;
                var url = "http://" + location.hostname + ":8080/cmpImages/images/";
                url = url + date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + d.name;
                //先绑定图片到模态框上面
                $("#image").attr("src", url);

                /* 完成拖拽 */
                $("#myModal").draggable({
                    cursor: "move"
                    //handle: '.modal-header'--指定只有拖拽头部，才能拖拽
                });
                //显示模态框
                $("#myModal").modal("show");
                document.getElementById("catch1").disabled = false;
            }else {
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.open({
                        type: 1
                        ,offset: 'r' //具体配置参考：offset参数项
                        ,content: '<div style="padding: 20px 80px;">'+result.message+'</div>'
                        ,btn: '关闭'
                        ,btnAlign: 'c' //按钮居中
                        ,shade: 0 //不显示遮罩
                        ,yes: function(){
                            layer.closeAll();
                        }
                    });
                });
            }
        },
        "error": function (data) {
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.open({
                    type: 1
                    ,offset: 'r' //具体配置参考：offset参数项
                    ,content: '<div style="padding: 20px 80px;">'+result.message+'</div>'
                    ,btn: '关闭'
                    ,btnAlign: 'c' //按钮居中
                    ,shade: 0 //不显示遮罩
                    ,yes: function(){
                        layer.closeAll();
                    }
                });
            });
            document.getElementById("catch1").disabled = false;
        }
    });
}

//截取函数
function subVideo() {
    //先判断有没有开始跟结束时间
    if (start === null || start === '') {
        alert("请选择视频截取起点");
        return;
    }
    if (end === null || end === '') {
        alert("请选择视频截取终点");
        return;
    }
    if (start > end) {
        start = '';
        end = '';
        alert("截取终点时间不能小于截取起点时间!请重新开始截取");
        return;
    }
    document.getElementById("subVideo").disabled = true;
    $.ajax({
        "type": "post",
        "url": r.base_path + 'image/subVideo?' + new Date().getTime(),
        "dataType": "json",
        "data": {
            start: start,
            end: end,
            url: now_url,
            planUid: major_plan.uid
        },
        "success": function (data) {
            alert(data.message);
            document.getElementById("subVideo").disabled = false;
        },
        "error": function (data) {
            alert("视频截取失败");
            document.getElementById("subVideo").disabled = false;
        }
    });
}